import { Title } from '@/components/common';
import { tr } from '@/components/common/formatmessage';
import SmartModal from '@/components/smartmodal';
import {
  accountFindUserAPI,
  getRootDirectoryAPI,
  getSubDirectoryAPI,
  getUserByDirectoryAPI,
} from '@/services/selectors';
import { checkIsSupplier, MODAL_FOOTER_HEIGHT, MODAL_HEADER_HEIGHT, MODAL_PADDING_HEIGHT } from '@/utils/utils';
import { Button, Col, Row, Tooltip } from 'antd';
import { Grid, Header, SchemaForm } from 'gantd';
import _ from 'lodash';
import type { ReactNode } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { getUserInfo } from '@/utils/user';
import { skipRowObj } from './components/skip';
import { alluserSchema, usertableSchema, transferSearchSchema, alluserSearchSchema } from './schema';
import styles from './style.less';

interface SelectorModalProps {
  title?: string | ReactNode;
  visible: boolean;
  confirmLoading?: boolean;
  multiple?: boolean;
  onChange?: (selectedRowKeys: string[], selectedRows: any[]) => void;
  onCancel: () => void;
  onOk?: (selectedRowKeys: string[], selectedRows: any[]) => void;
  isActive?: boolean; // 是否过滤【有效】人员
  isShowSkipButton?: boolean; // 是否显示跳过按钮
  [propName: string]: any;
}

interface obj {
  id: string;
  leaf: boolean;
  name: string;
  path: any;
  type: string;
}

const params = {
  filterInfo: {
    name: '',
    excludeIds: [],
  },
  pageInfo: {
    pageSize: 50, // 理论上，会有问题，但是考虑如果输入多一点，检索精确度提高，一般没问题
  },
};

// 进阶检索弹框
function SelectorModal(props: SelectorModalProps) {
  const {
    users,
    defaultValue,
    valueProp,
    title,
    visible,
    multiple,
    onOk,
    onCancel,
    isActive = false,
    isShowSkipButton = true,
  } = props;

  const { isSupplier, showAlluserSearchSchema, showAlluserSchema } = useMemo(() => {
    // 当前用户为供应商
    const isSupplier = checkIsSupplier();

    const filterFn = (item: { fieldName: string }) =>
      isSupplier ? !['organizationId'].includes(item.fieldName) : true;

    // 过滤显示的用户列表Grid列配置
    const showAlluserSearchSchema = alluserSearchSchema.filter(filterFn);
    // 已选用户列表Grid列配置
    const showAlluserSchema = alluserSchema.filter(filterFn);

    return {
      isSupplier,
      showAlluserSearchSchema,
      showAlluserSchema,
    };
  }, []);

  //通过搜索框搜索出的用户列表
  const [searchData, setSearchData] = useState([]);

  //搜索框里面的输入值
  const [searchValue, setSearchValue] = useState('');

  // 左侧 展示数据，gird（右侧/用户）选择绑定数据
  const [value, setValue] = useState<any>(multiple ? [] : undefined); // 依据单选多选，设置初始值，统一和基本组件的数据

  // 传递给父级的 数组数据，gird（右侧/用户）选择绑定数据
  const [rowsVal, setRowsVal] = useState<any>();

  // 弹框高度和宽度设置
  const [modalHeight, setModalHeight] = useState(0);
  // const [modalWidth, setModalWidth] = useState(0);

  // 左侧grid，目录分类，组类别 数据
  const [categoryUserDataSource, setcategoryUserDataSource] = useState<obj[]>([]);

  const [deleteLoading, setDeleteLoading] = useState(false);

  // query,输入检索参数
  const [excludeIds, setexcludeIds] = useState<any>([]);

  // 右侧grid，用户 数据
  const [userList, setUserList] = useState([]);

  // grid（左侧/组类）目录分类，选择绑定数据
  const [, setSelectedRowKeys] = useState<string[]>([]);
  const [, setSelectedRows] = useState<any[]>([]);

  //已选用户，选择数据绑定
  const [, setSelectedUserRowKeys] = useState<string[]>([]);
  const [selectedUserRows, setSelectedUserRows] = useState<any[]>([]);

  // 弹窗尺寸变化回调
  const onModalSizeChange = useCallback((width: number, height: number) => {
    // setModalWidth(width)
    setModalHeight(height);
  }, []);

  // 表格高度数据
  const tableHeight = useMemo(() => {
    return modalHeight - MODAL_PADDING_HEIGHT - MODAL_HEADER_HEIGHT - MODAL_FOOTER_HEIGHT - 120;
  }, [modalHeight]);

  // 获取用户选择根目录
  const getRootDirectory = useCallback(async () => {
    const res = await getRootDirectoryAPI();
    const newData = res.map((item: any) => {
      return {
        ...item,
        path: [item.id],
      };
    });
    setcategoryUserDataSource(newData);
  }, []);

  // 实时搜索方法
  const onSearch = useCallback(
    async (inputMsg) => {
      if (inputMsg.userLoginName) {
        setSearchValue(inputMsg.userLoginName);
        let newData: any = [];
        if (users) {
          let value = false;
          if (/[a-z]/i.test(inputMsg.userLoginName)) {
            value = inputMsg.userLoginName.toLowerCase();
          }
          newData = users.filter((item: any) => {
            if (item.userName.includes(inputMsg.userLoginName)) {
              return {
                id: item.userId,
                userName: item.userName,
                userLoginName: item.userLoginName,
                organizationId: item.organizationId,
                email: item.email,
                isActive: item.isActive,
              };
            }
            if (value && item.userLoginName.includes(inputMsg.userLoginName)) {
              return {
                id: item.userId,
                userName: item.userName,
                userLoginName: item.userLoginName,
                organizationId: item.organizationId,
                email: item.email,
                isActive: item.isActive,
              };
            }
          });
        } else {
          const data = await accountFindUserAPI({
            ...params,
            filterInfo: { ...params.filterInfo, name: inputMsg.userLoginName, excludeIds },
          });
          // 数据处理
          newData = data.map((item: any) => {
            return {
              id: item.userId,
              userName: item.userName,
              userLoginName: item.userLoginName,
              organizationId: item.organizationId,
              email: item.email,
              isActive: item.isActive,
            };
          });
        }

        if (isActive) {
          newData = newData.filter((item) => item.isActive);
        }

        setSearchData(newData);
      } else {
        setSearchValue('');
        setSearchData([]);
        setUserList([]);
      }
    },
    [users, isActive, excludeIds],
  );

  // 异步加载数据，根据 组 类 查找获得 children 的 组 类
  const serverGroupExpend = useCallback(async (gridParams, cb) => {
    const { data: record } = gridParams;
    const newData = await getSubDirectoryAPI({
      parentId: record.id,
      parentType: record.type,
    });
    const nnewData = newData.map((item: any) => {
      return {
        ...item,
        path: [...record.path, item.id],
      };
    });
    cb(nnewData, nnewData.length);
  }, []);

  const treeDataArr = useCallback((data) => {
    const { path } = data;
    return path;
  }, []);

  // 用户数据获取
  const selectUserFun = useCallback(
    async (id) => {
      let res = [];
      if (id) {
        // 在拥有id数值的时候，发起请求
        const origin = await getUserByDirectoryAPI({ id });
        // 统一 各小组件间 数据格式，方便交流
        res = origin.map((item: any) => ({
          id: item.userId,
          userLoginName: item.userLoginName,
          userName: item.userName,
          organizationId: item.organizationId,
          email: item.email,
          isActive: item.isActive,
        }));
        if (props.isActive) {
          res = res.filter((item: any) => item.isActive === props.isActive);
        }
      } else {
        // 在没选选择项，或者取消勾选的情况下清空用户数据
        res = users || []; // users ???
      }
      setUserList(res);
    },
    [users, props.isActive],
  );

  // grid 选择项配置
  const rowSelection = useMemo(() => {
    return {
      type: multiple ? 'multiple' : 'single',
      onSelect: (keys: any, rows: any) => {
        // 统一数据格式
        const data = rows.map((item: any) => {
          return item[valueProp];
        });
        if (multiple) {
          setValue(data); // 数据
          setRowsVal(rows); // 列表数据
        } else {
          const row = rows.pop();
          const val = _.get(row, valueProp);
          setValue(val || rowsVal[0]?.id);
          setRowsVal(row ? [row] : rowsVal);
        }
      },
      // selectedKeys: multiple ? value : [value], // grid选中数据绑定 已选中的数据
      selectedRows: rowsVal, // grid选中数据绑定 已选中的数据
    };
  }, [rowsVal, multiple, valueProp]);

  const onselect = useCallback((keys: any, rows: any) => {
    setSelectedUserRowKeys(keys);
    setSelectedUserRows(rows);
  }, []);

  const onDelete = useCallback(() => {
    setDeleteLoading(true);
    setSelectedUserRowKeys([]);
    setSelectedUserRows([]);
    if (!multiple) {
      setValue([]);
      setRowsVal([]);
    } else {
      const newrowsVal = _.differenceBy(rowsVal, selectedUserRows, 'id');
      setRowsVal(newrowsVal);
      const newValue = newrowsVal.map((val) => {
        return val[valueProp];
      });
      setValue(newValue);
    }
    setTimeout(() => {
      setDeleteLoading(false);
    }, 500);
  }, [multiple, valueProp, rowsVal, selectedUserRows]);

  // 确认添加
  const onsubmit = useCallback(() => {
    if (multiple) {
      onOk &&
        onOk(
          value?.filter((id: any) => id !== skipRowObj.id),
          rowsVal?.filter((row: any) => row.id !== skipRowObj.id),
        );
    } else {
      onOk && onOk(value, rowsVal);
    }
  }, [rowsVal, value, onOk, multiple]);

  const onsubmitSkip = useCallback(() => {
    onOk && onOk([skipRowObj.id], [skipRowObj]);
  }, [onOk]);

  // 监控弹框的状态，处理对应的数据状况
  useEffect(() => {
    // 关闭 进阶操作弹窗 的同时，清空重置数据
    if (!visible) {
      setValue([]);
      setRowsVal([]);
      setexcludeIds([]); // query 数据
      setUserList([]); // grid 用户分类数据
      setSearchData([]);
      setSearchValue('');
      setSelectedUserRowKeys([]);
      setSelectedUserRows([]);
    } else {
      // 打开 进阶操作弹框 的同事，数据处理
      if (!defaultValue || defaultValue.length === 0) return;
      const isLoginName = valueProp && valueProp === 'userLoginName';
      // 多选的条件
      if (multiple) {
        // 处理默认值数据（多选）
        const arr = defaultValue.map((item: any) => {
          const record = isLoginName ? getUserInfo('', item) : getUserInfo(item);
          return {
            id: record.id,
            userName: record.userName,
            userLoginName: record.userLoginName,
            organizationId: record.organizationId,
          };
        });
        setRowsVal(arr);
        setValue(defaultValue);
        setexcludeIds(defaultValue);
      } else {
        // 处理默认值数据（单选）
        const record = isLoginName ? getUserInfo(undefined, defaultValue) : getUserInfo(defaultValue);
        setRowsVal([
          {
            id: record.id,
            userName: record.userName,
            userLoginName: record.userLoginName,
            organizationId: record.organizationId,
            email: record.email,
          },
        ]);
        setValue(record[valueProp]);
        setexcludeIds([record.id]);
      }
    }
  }, [visible, valueProp, defaultValue, multiple]);

  // 监控users数据，随时更新用户选择
  useEffect(() => {
    if (!users && visible) {
      getRootDirectory();
    } else {
      // 默认展示一条数据
      const categoryObj = {
        id: '',
        leaf: true,
        name: '预设目录',
        path: [''],
        type: 'ORGANIZATION_ROOT',
      };
      setcategoryUserDataSource([categoryObj]);
    }
  }, [users, visible, getRootDirectory]);

  return (
    <SmartModal
      id="newUserSelector"
      title={title}
      visible={visible}
      itemState={{ width: '75%', height: '75%' }}
      maxZIndex={1100}
      onSizeChange={onModalSizeChange}
      onCancel={onCancel}
      footer={
        <>
          <Button size="small" onClick={onCancel}>
            {tr('取消')}
          </Button>
          <Button type="primary" size="small" onClick={onsubmit}>
            {tr('确认')}
          </Button>
          {isShowSkipButton && (
            <Button type="danger" size="small" onClick={onsubmitSkip}>
              {tr('【跳过该结点人选】')}
            </Button>
          )}
        </>
      }
    >
      {/* 顶部搜索区域 */}
      <Row>
        <Col span={24} className={styles.userSelector}>
          {/* 登录名输入 */}
          <div onKeyDown={(e: any) => e.stopPropagation()}>
            <SchemaForm schema={transferSearchSchema} onChange={onSearch} />
          </div>
        </Col>
      </Row>

      {/* 3列展示区域 */}
      <Row justify="space-between" style={{ marginTop: '10px' }} type="flex">
        {/* 供应商搜索 */}
        {(isSupplier || searchValue) && (
          <Col style={{ width: '66%' }}>
            <Header title={<Title title={tr('用户列表')} />} type="line" />
            <Grid
              gridKey="userByDirectory"
              rowkey={(data) => data.userId || data.id}
              columns={showAlluserSearchSchema}
              dataSource={searchData}
              height={tableHeight}
              rowSelection={rowSelection}
              hideMenuItemExport
              groupSuppressAutoColumn
              suppressColumnVirtualisation
              hideSelcetedBox
              loading={deleteLoading}
            />
          </Col>
        )}

        {/* 非供应商搜索 -- 默认 */}
        {!(isSupplier || searchValue) && (
          <>
            <Col style={{ width: '32.6%' }}>
              <Header title={<Title title={tr('目录分类')} />} type="line" />
              <Grid
                gridKey="userBySearch"
                rowkey="id"
                columns={usertableSchema}
                height={tableHeight}
                dataSource={categoryUserDataSource} // grid数据源
                rowSelection={{
                  type: multiple ? 'multiple' : 'single',
                  onSelect: (keys: any, rows: any) => {
                    setSelectedRowKeys(keys);
                    setSelectedRows(rows);
                    selectUserFun(keys[0]);
                  },
                  // selectedRows,
                  // selectedKeys: selectedRowKeys,
                }}
                treeData
                hideMenuItemExport
                groupSuppressAutoColumn
                suppressColumnVirtualisation
                isCompute={false}
                isServerSideGroup={(data: any) => {
                  return !data.leaf;
                }}
                getDataPath={(data) => treeDataArr(data)}
                serverGroupExpend={serverGroupExpend}
              />
            </Col>
            <Col style={{ width: '32.6%' }}>
              <Header title={<Title title={tr('用户列表')} />} type="line" />
              <Grid
                gridKey="userByDirectory"
                rowkey={(data) => data.userId || data.id}
                columns={alluserSchema}
                dataSource={userList}
                height={tableHeight}
                rowSelection={rowSelection}
                hideMenuItemExport
                groupSuppressAutoColumn
                suppressColumnVirtualisation
                hideSelcetedBox
                loading={deleteLoading}
              />
            </Col>
          </>
        )}

        {/* 已选用户 */}
        <Col style={{ width: '32.6%' }}>
          <Header
            title={<Title title={tr('已选用户')} />}
            type="line"
            extra={
              <>
                <Tooltip title={tr('删除')}>
                  <Button
                    size="small"
                    icon="delete"
                    type="danger"
                    onClick={onDelete}
                    disabled={!selectedUserRows || selectedUserRows.length == 0}
                  />
                </Tooltip>
              </>
            }
          />
          <Grid
            gridKey="selectedUserList"
            rowkey={(data: any) => data.userId || data.id}
            columns={showAlluserSchema}
            dataSource={rowsVal}
            height={tableHeight}
            rowSelection={{
              type: multiple ? 'multiple' : 'single',
              onSelect: onselect,
              selectedRows: selectedUserRows,
            }}
            hideMenuItemExport
            groupSuppressAutoColumn
            suppressColumnVirtualisation
            hideSelcetedBox
            loading={deleteLoading}
          />
        </Col>
      </Row>
    </SmartModal>
  );
}

// 组件默认的 props 值
SelectorModal.defaultProps = {
  // value: [],
  title: tr('选择用户'),
  itemState: { width: 1008, height: 650 },
  loading: false,
  zIndex: 1007,
  valueProp: 'id',
  // 需要统一，selector数据和grid数据的互通关系，不要自定义
  // labelProp: 'combineLabel',
  labelProp: 'userName',
  multiple: false,
};

export default React.memo(SelectorModal);
